package com.bw.lib_common.widget.nine_pic_grid

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.bw.lib_common.R

/**
 * @author ytx
 * @date 2025-09-26 08:04
 * @description
 * 自定义九宫格朋友圈
 * 1.视频:横向还是纵向显示视频第一帧
 * 2.图片数量：
 *  1张图片：横向还是纵向
 *  2张以上：九宫格
 *
 */
class NineGridPicsView :FrameLayout{
    private val mParentView:View
    private val mRvPic: RecyclerView
    private var mPicsList:List<Image>? = null
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        mParentView = LayoutInflater.from(context).inflate(R.layout.layout_nine_grid_pics_view, this) as ViewGroup
        mRvPic = mParentView.findViewById(R.id.rv_pic_9)
    }
    private var onItemClick:((Int,Image) ->  Unit)? = null

    fun setOnItemClick(onItemClick:((Int,Image) ->  Unit)?){
        this.onItemClick = onItemClick
    }

    /**
     * 设置图片数据
     */
    fun setData(picList:List<Image>){
       this.mPicsList = picList
    }
    /**
     * 加载view:图片放在recyclerview展示
     */
    fun initView(){
        if (mPicsList.isNullOrEmpty()){
            return
        }
        val column = if (mPicsList!!.size == 1) 1 else 3
        val gridLayout = object :GridLayoutManager(context,column, GridLayoutManager.VERTICAL,false){
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRvPic.layoutManager = gridLayout
        mRvPic.adapter = NinePicsAdapter(mPicsList!!){position->
            onItemClick?.invoke(position,mPicsList!![position])
        }
        (mRvPic.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //取消动画，提高滑动顺畅
    }

}